<?php
/**
 * TomatoCMS
 *
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@tomatocms.com so we can send you a copy immediately.
 *
 * @copyright    Copyright (c) 2009-2010 TIG Corporation (http://www.tig.vn)
 * @license        http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @version     $Id: AssignmentController.php 3075 2010-05-26 15:41:59Z huuphuoc $
 */

class Assignment_AssignmentController extends Zend_Controller_Action
{
    /** ========== Backend actions =========================================== */

    /**
     * Get list all assignment
     * @return void
    **/
    public function listAction()
    {
        $request = $this->getRequest();

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Assignment access to db
         */
        $assignmentDao = Tomato_Model_Dao_Factory::getInstance()->setModule('assignment')->getAssignmentDao();
        $assignmentDao->setDbConnection($conn);

        /**
        * Enterprise User model access to db
        */
        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
        $userAccountDao->setDbConnection($conn);

        /**
        * User model access to db
        */
        $userDao = Tomato_Model_Dao_Factory::getInstance()->setModule('core')->getUserDao();
        $userDao->setDbConnection($conn);

        $pageIndex = $request->getParam('pageIndex', 1);
        $perPage   = 20;
        $offset    = ($pageIndex - 1) * $perPage;
        $purifier     = new HTMLPurifier();

        /**
         * Build product search expression
         **/
        $params = null;
        $exp = array();

        /**
        * Get current user
        */
        $user = Zend_Auth::getInstance()->getIdentity();
        $userAccount = $userAccountDao->getByUser($user->user_id);

        /**
         * Get information for filter
         * $a_process: array object assignment process with type = 1
         * $role: Role of producer
        **/
        $a_process = $assignmentDao->getPByType(1);
        $arrStatusIdOfAssignment = array();
        foreach($a_process as $a_pro){
            $arrStatusIdOfAssignment[$a_pro->status_id] = $a_pro->status_id;
        }

        /**
         * Get status for filter selectbox
         * $arrSStatus: store status info
         **/
        $arrSStatus = array();
        if($arrStatusIdOfAssignment){
            foreach($arrStatusIdOfAssignment as $s_id){
                $ojStatus = $assignmentDao->getSSById($s_id);
                $arrSStatus[] = $ojStatus;
            }
        }
        $this->view->assign('arrSStatus', $arrSStatus);

        /**
         * Get all producer to selectbox for assignment
        **/
        $role = $assignmentDao->getRoleByName('nhan vien san xuat');
        $arrSProducer = array();
        if(isset($userAccount->enterprise_id)){
            $userOfEnterPrise = $userAccountDao->getUserAccountBy($userAccount->enterprise_id);
            foreach($userOfEnterPrise as $e_user){
                if($role->role_id == $e_user->role_id){
                    $arrSProducer[] = $e_user;
                }
            }
        }
        $this->view->assign('arrSProducer', $arrSProducer);

        /**
        * Check permission all list assignment
        */
        if(!Core_Services_RuleChecker::isAllowed('all-list')){
            if($userAccount){
                $enterprise_id = (null != $userAccount->enterprise_id)?$userAccount->enterprise_id:null;
                $exp['enterprise_id'] = $purifier->purify($enterprise_id);
            }else{
                die('Not found enterpise id');
            }
        }

        /**
        * Check permission all list assignment of company
        */
        if(!Core_Services_RuleChecker::isAllowed('company-list')){
            if($user){
                $u_id = $user->user_id;
                $exp['producer_account_id'] = $u_id;
                $exp['assigner_account_id'] = $u_id;
            }
        }

        if($request->isPost()){
            $assignment_status   = $request->getPost('assignment_status');
            $from_create_date    = $request->getPost('from_create_date');
            $to_create_date      = $request->getPost('to_create_date');
            $from_due_date       = $request->getPost('from_due_date');
            $to_due_date         = $request->getPost('to_due_date');
            $assignment_producer = $request->getPost('assignment_producer');
            $order_invoice       = $request->getPost('order_invoice');
            $sort_product_name   = $request->getPost('sort_product_name');
            $sort_create_date    = $request->getPost('sort_create_date');

            /**
            * Check condition filter
            **/
            if('all' != $assignment_status){
                $exp['assignment_status'] = $assignment_status;
                $f_process = $assignmentDao->getPBySId($assignment_status);
                if(count($f_process) > 0){
                    $str_cond = null;
                    $i = 0;
                    foreach($f_process as $p_row){
                        $cond = "a.`process_id` = {$p_row->process_id}";
                        $cond1 = " or a.`process_id` = {$p_row->process_id}";
                        $str_cond .= ($i==0)?$cond:$cond1;
                        $i++;
                    }
                    $exp['process_id'] = $str_cond;
                }
            }
            if($from_create_date){
                $from_create_date = date('Y-m-d',strtotime($this->convertDateFormat($from_create_date)));
                $exp['assignment_create_from_date'] = $from_create_date;
            }
            if($to_create_date){
                $to_create_date = date('Y-m-d',strtotime($this->convertDateFormat($to_create_date)));
                $exp['assignment_create_to_date'] = $to_create_date;
            }
            if($from_due_date){
                $from_due_date = date('Y-m-d',strtotime($this->convertDateFormat($from_due_date)));
                $exp['assignment_due_from_date'] = $from_due_date;
            }
            if($to_due_date){
                $to_due_date = date('Y-m-d',strtotime($this->convertDateFormat($to_due_date)));
                $exp['assignment_due_to_date'] = $to_due_date;
            }
            if('all' != $assignment_producer){
                $exp['assignment_producer'] = $assignment_producer;
            }
            if($order_invoice){
                $exp['order_invoice'] = $order_invoice;
            }
            if($sort_product_name){
                $exp['sort_product_name'] = $sort_product_name;
            }
            if($sort_create_date){
                $exp['sort_create_date'] = $sort_create_date;
            }
            $params = rawurlencode(base64_encode(Zend_Json::encode($exp)));
        }
        else {
            $params = $request->getParam('q');
            if (null != $params) {
                $exp = rawurldecode(base64_decode($params));
                $exp = Zend_Json::decode($exp);
            } else {
                $params = rawurlencode(base64_encode(Zend_Json::encode($exp)));
            }
        }
        $assignments = $assignmentDao->find($offset, $perPage, $exp);
        $total       = $assignmentDao->count($exp);

        /**
         * Declaration variable and assign value default
         * $arrProduct: Store product info for assignment
         * $arrProducer: Store producer info for assignment
         * $arrAssigner: Store assigner info for assignment
         * $arrDueDate: Store due date for assignment
         * $arrDueDate: Store status name of assignment
         * $arrAssignments : Store all assignment after check due_date sorting
        **/
        $arrProduct     = array();
        $arrProducer    = array();
        $arrAssigner    = array();
        $arrDueDate     = array();
        $arrStatus      = array();
        $arrAssignments = array();

        $index = 0;
        foreach($assignments as $assignment){
            /**
            * Get product info for assignment
            **/
            if($assignment->order_detail_id){
                $product = $assignmentDao->getODById($assignment->order_detail_id);
                $arrProduct[$assignment->assignment_id] = $product;
            }

            /**
             * Get producer info for asssignment
            **/
            if($assignment->producer_account_id){
                $producer = $userDao->getById($assignment->producer_account_id);
                $arrProducer[$assignment->assignment_id] = $producer;
            }

            /**
             * Get assigner info for asssignment
            **/
            if($assignment->assigner_account_id){
                $assigner = $userDao->getById($assignment->assigner_account_id);
                $arrAssigner[$assignment->assignment_id] = $assigner;
            }

            /**
             * Calculated due date
            **/
            /*$dueDate = null;
            if(isset($product)){
                if($product->production_duration){
                    $numDay   = $product->production_duration;
                    $seconds  = $numDay*24*60*60;
                    $intTime  = strtotime($assignment->assignment_create_date)+$seconds;
                    $dueDate = date("d-m-Y",$intTime);
                }
            }
            $arrDueDate[$assignment->assignment_id] = $dueDate;*/

            /**
             * Get status for assignment
            **/
            if($assignment->process_id){
                $status = $assignmentDao->getPSById($assignment->process_id);
                $arrStatus[$assignment->assignment_id] = $status->code;
            }

            /**
             * Create array assignment to sort
             **/
            $arrAssignments[$index][0] = $product->product_admin_name;
            $arrAssignments[$index][1] = $assignment->assignment_create_date;
            $arrAssignments[$index][2] = $assignment;
            $index++;
        }
        $this->view->assign('arrProduct', $arrProduct);
        $this->view->assign('arrProducer', $arrProducer);
        $this->view->assign('arrAssigner', $arrAssigner);
        $this->view->assign('arrDueDate', $arrDueDate);
        $this->view->assign('arrStatus', $arrStatus);

        /**
        * Storting with product name or create date
        **/
        if(isset($exp['sort_create_date'])){
            $arrAssignments = $this->array_sort($arrAssignments, 1);
        }
        if(isset($exp['sort_product_name'])){
            $arrAssignments = $this->array_sort($arrAssignments, 0, 'SORT_ASC');
        }
        $arrAssignmentsSorted = array();
        foreach($arrAssignments as $r_assignment){
            $arrAssignmentsSorted[] = $r_assignment[2];
        }

        /**
        * Paginator
        */
        $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($assignments, $total));
        $paginator->setCurrentPageNumber($pageIndex);
        $paginator->setItemCountPerPage($perPage);

        $this->view->assign('exp', $exp);
        $this->view->assign('pageIndex', $pageIndex);
        $this->view->assign('assignments', $arrAssignmentsSorted);
        $this->view->assign('numAssignment', $total);

        $this->view->assign('paginator', $paginator);
        $this->view->assign('paginatorOptions', array(
            'path'        => $this->view->url(array(), 'assignment_assignment_list'),
            'itemLink' => (null == $params)
                            ? 'page-%d/'
                            : 'page-%d/?q=' . $params,
        ));
    }

    /**
    * View detail assignment info
    * @return void
    **/
    public function viewAction()
    {
        $request = $this->getRequest();
        $id = $request->getParam('assignment_id');

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Assignment access to db
         */
        $assignmentDao = Tomato_Model_Dao_Factory::getInstance()->setModule('assignment')->getAssignmentDao();
        $assignmentDao->setDbConnection($conn);

        /**
        * Enterprise User model access to db
        */
        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
        $userAccountDao->setDbConnection($conn);

        /**
        * User model access to db
        */
        $userDao = Tomato_Model_Dao_Factory::getInstance()->setModule('core')->getUserDao();
        $userDao->setDbConnection($conn);

        /**
        * Attribute model access to db
        */
        $attributeDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getAttributeDao();
        $attributeDao->setDbConnection($conn);

        /**
        * Value model access to db
        */
        $valueDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getValueDao();
        $valueDao->setDbConnection($conn);

        /**
         * Get assignment info
        **/
        $assignment = $assignmentDao->getById($id);
        $this->view->assign('assignment', $assignment);

        /**
        * Get product info for assignment
        **/
        $product = null;
        if($assignment->order_detail_id){
            $product = $assignmentDao->getODById($assignment->order_detail_id);
        }
        $this->view->assign('product', $product);

        /**
         * Get attribute and value for product info
         **/
        $arrAtVal = array();
        if($product){
            $at_val_chian = $product->product_value_type_id_chain;
            if($at_val_chian){
                $arrAtValId = Zend_Json::decode($at_val_chian);
                foreach($arrAtValId as $key=>$row){
                    $attriubte = $attributeDao->getAttributeById($key);
                    $value = $valueDao->getById($row);
                    $arrAtVal[] = array($attriubte->attribute_type_admin_name, $value->value_type_name);
                }
            }
        }
        $this->view->assign('arrAtVal',$arrAtVal);

        /**
         * Get customer id to assign for widget customerinfo
         * $customer_id Id of user with order
         * $customer_notice : Notice of customer for order
        **/
        $customer_id = null;
        $customer_notice = null;
        if(isset($assignment->order_id)){
            $customer = $assignmentDao->getOrderById($assignment->order_id);
            if($customer){

                $customer_id = $customer->customer_id;
                $customer_notice = $customer->customer_notice;
            }
        }
        $this->view->assign('customer_id', $customer_id);
        $this->view->assign('customer_notice', $customer_notice);

        /**
        * Get current user
        */
        $user = Zend_Auth::getInstance()->getIdentity();
        $this->view->assign('user', $user);
        $userAccount = $userAccountDao->getByUser($user->user_id);

        /**
        * Check permission all list assignment
        */
        $isAllowed = true;
        if(!Core_Services_RuleChecker::isAllowed('all-list')){
            if(isset($userAccount->enterprise_id) && isset($product->enterprise_id)){
                if($userAccount->enterprise_id != $product->enterprise_id){
                    $isAllowed = false;
                    $this->view->assign('isAllowed', $isAllowed);
                    return;
                }
            }
        }

        /**
        * Check permission all list assignment of company
        */
        if(!Core_Services_RuleChecker::isAllowed('company-list')){
            if($user->user_id != $assignment->producer_account_id && $user->user_id != $assignment->assigner_account_id){
                $isAllowed = false;
                $this->view->assign('isAllowed', $isAllowed);
                return;
            }
        }
        $this->view->assign('isAllowed', $isAllowed);

        /**
         * Get producer info to view for asssignment
        **/
        $producer = null;
        if($assignment->producer_account_id){
            $producer = $userDao->getById($assignment->producer_account_id);
        }
        $this->view->assign('producer', $producer);

        /**
         * Get assigner info for asssignment
        **/
        $assigner = null;
        if($assignment->assigner_account_id){
            $assigner = $userDao->getById($assignment->assigner_account_id);
        }
        $this->view->assign('assigner', $assigner);

        /**
         * Calculated due date
        **/
        /*$dueDate = '-';
        if(isset($product)){
            if($product->production_duration){
                $numDay   = $product->production_duration;
                $seconds  = $numDay*24*60*60;
                $intTime  = strtotime($assignment->assignment_create_date)+$seconds;
                $dueDate = date("d-m-Y",$intTime);
            }
        }
        $this->view->assign('dueDate', $dueDate);*/

        /**
         * Get status for assignment
        **/
        $status = null;
        $objstatus = null;
        if($assignment->process_id){
            $objstatus = $assignmentDao->getPSById($assignment->process_id);
            if($objstatus){
                $status =$objstatus->code;
            }
        }
        $this->view->assign('status', $status);

        /**
         * Get follow process for assignment
        **/
        $arrProcess = array();
        if($objstatus){
            $arrProcess = explode(',',substr(substr($objstatus->follow_process_id_chain,1),0,-1));
        }
        $this->view->assign('arrProcess', $arrProcess);

        /**
         * Get follow step for assignment
        **/
        $arrSteps = array();
        if($objstatus){
            $arrFollowSteps = explode(',',substr(substr($objstatus->follow_step_id_chain,1),0,-1));
            foreach($arrFollowSteps as $row){
                $steps = $assignmentDao->getSSById($row);
                if($steps){
                    $arrSteps[] = $steps;
                }
            }
        }
        $this->view->assign('arrSteps', $arrSteps);

        /**
         * Get all producer to selectbox for assignment
        **/
        $arrProducer = array();
        if(isset($userAccount->enterprise_id)){
            $userOfEnterPrise = $userAccountDao->getUserAccountBy($userAccount->enterprise_id);
            foreach($arrSteps as $step){
                if($step->receiver_role_id_chain != ',' && strstr($step->performer_role_id_chain,','.$user->role_id.',')){
                    foreach($userOfEnterPrise as $e_user){
                        if(strstr($step->receiver_role_id_chain, ','.$e_user->role_id.',')){
                            $arrProducer[] = $e_user;
                        }
                    }
                }
            }
        }
        $this->view->assign('arrProducer', $arrProducer);

        if($request->isPost()){
            $assignment_id    = $id;
            $process_id       = $request->getPost('process_id');
            if(!$process_id){
                $this->_helper->getHelper('FlashMessenger')
                ->addMessage($this->view->translator('assignment_please_choose_step'));
                $this->_redirect($this->view->serverUrl() . $this->view->url(array('assignment_id' => $id), 'assignment_assignment_view'));
                return;
            }
            $step_code = $request->getPost('step_code_'.$process_id);
            $producer_account_id = $request->getPost('producer_account_id');
            $assignment_finish_date = date('Y-m-d');
            $u_name = trim($user->full_name)?$user->full_name:$user->user_name;
            $old_notes = $assignment->assignment_notes;
            $assignment_notes = $request->getPost('assignment_notes').'<br/>'.$old_notes;
            $assignment_notes = '<b>('.date('d-m-Y').', '.$u_name.', '.$this->view->translator('assignment_step').': '.$this->view->translator('assignment_step_'.$step_code).')</b><br/>'.$assignment_notes;

            $assignment->assignment_id    = $assignment_id;
            $assignment->process_id       = $process_id;
            $assignment->assignment_notes = $assignment_notes;
            if($producer_account_id){
                $assignment->producer_account_id = $producer_account_id;
            }
            if($step_code == 'done'){
                $assignment->assignment_finish_date = $assignment_finish_date;
            }
            $result = $assignmentDao->update($assignment);
            if($result){
                $this->_helper->getHelper('FlashMessenger')
                ->addMessage($this->view->translator('assignment_update_status_success'));
            $this->_redirect($this->view->serverUrl() . $this->view->url(array('assignment_id' => $id), 'assignment_assignment_view'));
            }
        }
    }

    /**
    * Add assignment
    * @return void
    **/
    public function addJobAction(){
        $request = $this->getRequest();
        $order_id = $request->getParam('order_id');
        $this->view->assign('order_id', $order_id);

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Assignment access to db
         */
        $assignmentDao = Tomato_Model_Dao_Factory::getInstance()->setModule('assignment')->getAssignmentDao();
        $assignmentDao->setDbConnection($conn);

        /**
        * Enterprise User model access to db
        */
        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
        $userAccountDao->setDbConnection($conn);

        /**
        * User model access to db
        */
        $userDao = Tomato_Model_Dao_Factory::getInstance()->setModule('core')->getUserDao();
        $userDao->setDbConnection($conn);

        /**
         * order models access to data
         **/
        $orderDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getOrderDao();
        $orderDao->setDbConnection($conn);

        /**
        * Attribute model access to db
        */
        $attributeDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getAttributeDao();
        $attributeDao->setDbConnection($conn);

        /**
        * Value model access to db
        */
        $valueDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getValueDao();
        $valueDao->setDbConnection($conn);

        /**
        * Get current user
        */
        $user = Zend_Auth::getInstance()->getIdentity();
        $userAccount = $userAccountDao->getByUser($user->user_id);
        $this->view->assign('userAccount', $userAccount);
        /**
         * Get order by order id
         **/
        $order = $orderDao->getOrderById($order_id);

        /**
        * Check permission to view order detail
        **/
        $isAllowed = true;
        if(!Core_Services_RuleChecker::isAllowed('all-list','order','shop')){
            if(isset($userAccount->enterprise_id) && isset($order->enterprise_id)){
                if($userAccount->enterprise_id != $order->enterprise_id){
                    $isAllowed = false;
                    $this->view->assign('isAllowed', $isAllowed);
                    return;
                }
            }
        }
        $this->view->assign('isAllowed', $isAllowed);

        /**
         * Get process by process id = 1
        **/
        $objProcess = $assignmentDao->getPSById(1);

        /**
         * Get follow step for assignment
        **/
        $step = $assignmentDao->getSSById(substr(substr($objProcess->follow_step_id_chain,1),0,-1));

        /**
         * Check current user allow assign
         **/
        $assAllow = true;
        if(!strstr($step->performer_role_id_chain,','.$user->role_id.',')){
            $assAllow = false;
        }
        $this->view->assign('assAllow', $assAllow);

        /**
         * Get all producer to selectbox for assignment
        **/
        $arrProducer = array();
        if(isset($userAccount->enterprise_id)){
            $userOfEnterPrise = $userAccountDao->getUserAccountBy($userAccount->enterprise_id);
            if($step->receiver_role_id_chain != ',' && strstr($step->performer_role_id_chain,','.$user->role_id.',')){
                foreach($userOfEnterPrise as $e_user){
                    if(strstr($step->receiver_role_id_chain, ','.$e_user->role_id.',')){
                        $arrProducer[] = $e_user;
                    }
                }
            }

        }
        $this->view->assign('arrSProducer', $arrProducer);

        $exp = array();
        $exp['order_invoice'] = $order->order_invoice;

        /**
        * Check permission all list assignment
        */
        if(!Core_Services_RuleChecker::isAllowed('all-list')){
            if($userAccount){
                $enterprise_id = (null != $userAccount->enterprise_id)?$userAccount->enterprise_id:null;
                $exp['enterprise_id'] = $enterprise_id;
            }else{
                die('Not found enterpise id');
            }
        }

        /**
        * Check permission all list assignment of company
        */
        if(!Core_Services_RuleChecker::isAllowed('company-list')){
            if($user){
                $u_id = $user->user_id;
                $exp['producer_account_id'] = $u_id;
                $exp['assigner_account_id'] = $u_id;
            }
        }

        /**
        * Get assignment list of assigned
        **/
        $assignments = $assignmentDao->find(null, null, $exp);
        $this->view->assign('assignments', $assignments);

        /**
         * Declaration variable and assign value default
         * $arrProduct: Store product info for assignment
         * $arrProducer: Store producer info for assignment
         * $arrAssigner: Store assigner info for assignment
         * $arrDueDate: Store due date for assignment
         * strODId Store Order detail id chain
        **/
        $arrProduct     = array();
        $arrProducer    = array();
        $arrAssigner    = array();
        $arrStatus      = array();
        $strODId = ',';

        $index = 0;
        foreach($assignments as $assignment){
            /**
            * Get product info for assignment
            **/
            if($assignment->order_detail_id){
                $product = $assignmentDao->getODById($assignment->order_detail_id);
                $arrProduct[$assignment->assignment_id] = $product;
            }

            /**
             * Get producer info for asssignment
            **/
            if($assignment->producer_account_id){
                $producer = $userDao->getById($assignment->producer_account_id);
                $arrProducer[$assignment->assignment_id] = $producer;
            }

            /**
             * Get assigner info for asssignment
            **/
            if($assignment->assigner_account_id){
                $assigner = $userDao->getById($assignment->assigner_account_id);
                $arrAssigner[$assignment->assignment_id] = $assigner;
            }

            /**
             * Get status for assignment
            **/
            if($assignment->process_id){
                $status = $assignmentDao->getPSById($assignment->process_id);
                $arrStatus[$assignment->assignment_id] = $status->code;
            }

            /**
             * Get order id chain
             **/
            $strODId .= $assignment->order_detail_id.',';
        }
        $this->view->assign('arrProduct', $arrProduct);
        $this->view->assign('arrProducer', $arrProducer);
        $this->view->assign('arrAssigner', $arrAssigner);
        $this->view->assign('arrStatus', $arrStatus);

        /**
         * Get product list to assign
         **/
        $products = $orderDao->getProductById($order_id);

        /**
        * Get attribute and value of product in order
        * $arrAllAtVal Store attribute and value of product
        * $arrProduct Store product without product assigned
        **/
        $arrAllAtVal = array();
        $arrProducts = array();
        if($products){
            foreach($products as $product){
                if(!strstr($strODId, ','.$product->order_detail_id.',')){
                    $at_val_chian = $product->product_value_type_id_chain;
                    if($at_val_chian){
                        $arrAtValId = Zend_Json::decode($at_val_chian);
                        $arrAtVal = array();
                        foreach($arrAtValId as $key=>$row){
                            $attriubte = $attributeDao->getAttributeById($key);
                            $value = $valueDao->getById($row);
                            $arrAtVal[] = array($attriubte->attribute_type_admin_name, $value->value_type_name);
                        }
                        $arrAllAtVal[$product->order_detail_id] = $arrAtVal;
                    }

                    /**
                    * Get product without product assigned
                    **/
                    $arrProducts[] = $product;
                }
            }
        }
        $this->view->assign('arrAllAtVal',$arrAllAtVal);
        $this->view->assign('products',$arrProducts);

        if($request->isPost()){
            $ckb_order_id = $request->getPost('ckb_order_id');
            if($ckb_order_id){
                foreach($ckb_order_id as $row){
                    if(!trim($request->getPost('producer_account_id')))
                    {
                        $this->_helper->getHelper('FlashMessenger')
                            ->addMessage($this->view->translator('assignment_please_choose_producer'));
                        $this->_redirect($this->view->serverUrl() . $this->view->url(array('order_id' => $order_id), 'assignment_assignment_add_job'));
                    }
                    /**
                    * Caculated due date
                    **/
                    $production_duration = $request->getPost('production_duration_'.$row);
                    $numDay   = $production_duration;
                    $seconds  = $numDay*24*60*60;
                    $intTime  = strtotime(date('Y-m-d'))+$seconds;
                    $dueDate = date("Y-m-d",$intTime);

                    /**
                     * Get process id
                     **/
                    $follow_process_id = substr(substr($objProcess->follow_process_id_chain,1),0,-1);

                    $assignment_add = new Assignment_Models_Assignment(array(
                                        'order_id'               => $request->getPost('order_invoice_'.$row),
                                        'order_detail_id'        => $row,
                                        'producer_account_id'    => $request->getPost('producer_account_id'),
                                        'assigner_account_id'    => $user->user_id,
                                        'assignment_create_date' => date('Y-m-d'),
                                        'assignment_due_date'    => $dueDate,
                                        'assignment_finish_date' => null,
                                        'process_id'             => $follow_process_id,
                                        'assignment_notes'       => null,
                                        'enterprise_id'          => $order->enterprise_id,
                    ));

                    $a_id = $assignmentDao->add($assignment_add);
                }
            }
            if($a_id){
            $this->_helper->getHelper('FlashMessenger')
                ->addMessage($this->view->translator('assignment_assign_success'));
            }
            $this->_redirect($this->view->serverUrl() . $this->view->url(array('order_id' => $order_id), 'assignment_assignment_add_job'));
        }
    }

    /**
     * Format date to strtotime function use
     * @return string
     */
    public function convertDateFormat($time){
        $a = explode("/", $time);
        $ts = $a[2].'/'.$a[1].'/'.$a[0];
        return $ts;
    }

    /**
     * Sort array
     * $array: array to sort
     * $on: index sort
     * $order: SORT_DESC or SORT_ASC
    **/
    public function array_sort($array, $on, $order='SORT_DESC')
    {
      $new_array = array();
      $sortable_array = array();

      if (count($array) > 0) {
          foreach ($array as $k => $v) {
              if (is_array($v)) {
                  foreach ($v as $k2 => $v2) {
                      if ($k2 == $on) {
                          $sortable_array[$k] = $v2;
                      }
                  }
              } else {
                  $sortable_array[$k] = $v;
              }
          }

          switch($order)
          {
              case 'SORT_ASC':
                  echo "ASC";
                  asort($sortable_array);
              break;
              case 'SORT_DESC':
                  echo "DESC";
                  arsort($sortable_array);
              break;
          }

          foreach($sortable_array as $k => $v) {
              $new_array[] = $array[$k];
          }
      }
      return $new_array;
    }
}